package com.xungou.global.controller;

import com.xungou.user.pojo.User;
import com.xungou.user.service.IUserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/global")
public class GlobalController {
    @Resource
    private IUserService userService;

    @RequestMapping("/registerPage")
    public String getPage() {
        return "global/register";
    }

    /**
     * 获取登录页面
     *
     * @return
     */
    @RequestMapping("/loginPage")
    public ModelAndView loginPage() {
        ModelAndView modelAndView = new ModelAndView();
        SecurityUtils.getSubject().logout();
        modelAndView.setViewName("global/login");
        return modelAndView;
    }

    @RequestMapping("/head")
    public String head() {
        return "global/head";
    }

    /**
     * 进行登录操作
     * @param params
     * @return
     */
    @RequestMapping("/login")
    @ResponseBody
    public Map<String,String> login(@RequestParam Map<String, String> params) {
        SecurityUtils.getSubject().logout();
        Map<String,String> result = new HashMap<String, String>();
        // 创建用户名和密码的令牌
        UsernamePasswordToken token = new UsernamePasswordToken(params.get("name"), params.get("password"));
        // 记录该令牌，如果不记录则类似购物车功能不能使用。
        token.setRememberMe(true);
        // subject理解成权限对象。类似user
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(token);
        } catch (AuthenticationException e) {// 其他的登录错误
            e.printStackTrace();
            result.put("flag", "0");
        }

        // 验证是否成功登录的方法
        if (subject.isAuthenticated()) {
            Session session = subject.getSession();
            User user = userService.getUserByName(params.get("name"));
            session.setAttribute("user",user);
            result.put("flag", "1");
            if(subject.hasRole("ADMIN"))
                result.put("page","user/manage.do");
            else
                result.put("page","user/index.do");
        }
        return result;
    }

    @RequestMapping("/register")
    @ResponseBody
    public int register(User user, Model model) {
        int flag = userService.register(user);
        return flag;
    }

    @RequestMapping("/isRepeat")
    @ResponseBody
    public int isRepeat(@RequestParam Map<String, String> params) {
        return userService.isRepeat(params);
    }
}
